package com.ph.custom.processor.handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import javax.servlet.ServletRequest;

/**
 * 
 * @ClassName:  CacheSelector   
 * @Description:缓存处理   主要针对增删改查
 * @author: lijie
 * @date:   2017年4月8日 下午12:09:26     
 */
public class CacheSelector implements InvocationHandler{

	private final Object proxied;

	/**
	 * 用户拦截非规则请求
	 */
	private static final String[] methods = { "update", "select", "delete", "insert" };

	public CacheSelector(Object proxied) {
		this.proxied = proxied;
	}
	/**
	 * 
	 * <p>Title: invoke</p>   
	 * <p>Description: </p>   
	 * @param proxy
	 * @param method
	 * @param args
	 * @return
	 * @throws Throwable   
	 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// 备注：此处暂时使用session 缓存数据 所以 HttpServletRequest 是必传参数
		Object obj = null;
		boolean flag = false;
		if (args != null && args.length > 0) {
			for (Object arg : args) {
				if (flag = (arg instanceof ServletRequest)) {
					break;
				}
			}
		}
		if (flag && isExistsMethod(method.getName())) {
			obj = method.invoke(proxied, args);
		}
		return obj;
	}
	/**
	 * 
	 * @Title: isExistsMethod   
	 * @Description: 判断调用的方法是否是该规则   
	 * @param: @param name
	 * @param: @return      
	 * @return: boolean      
	 * @throws
	 */
	private boolean isExistsMethod(String name) {
		boolean flag = false;
		for (String str : methods) {
			if (flag = name.startsWith(str)) {
				break;
			}
		}
		return flag;
	}
}
